package cn.yuhh.api.v1.common;

import cn.yuhh.api.exception.ApiException;
import cn.yuhh.api.helper.ApiResponse;
import cn.yuhh.api.service.AbstractApiService;
import cn.yuhh.core.util.FileUtil;
import cn.yuhh.core.util.UUIDGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * bird on 2017/6/1.
 */
@Component("upload1.0")
public class UploadPhotoService extends AbstractApiService {

    @Value("${image.upload.path}")
    private String path;
    @Value("${image.domain.url}")
    private String url;

    @Override
    public Map service(Map request) {
        List<Map> photoUrls = new ArrayList<>();
        MultipartFile[] multipartFiles = (MultipartFile[]) request.get("file");
        String selfId = selfId(request);
        try {
            for(MultipartFile multipartFile : multipartFiles){
                String fileName = multipartFile.getOriginalFilename();
                String newName = UUIDGenerator.uuid() + fileName.substring(fileName.lastIndexOf("."));
                FileUtil.write(path+selfId, newName, multipartFile.getBytes());
                photoUrls.add(new HashMap(){{
                    put("path", new StringBuilder(selfId + File.separator + newName).toString());
                    put("url", new StringBuilder(url+ selfId + File.separator + newName).toString());
                }});
            }
        } catch (IOException e) {
            throw new ApiException();
        }
        return ApiResponse.success(photoUrls);
    }


}
